<?php


namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;

class AwardCeremony extends Model
{
    // 表名
    protected $name = 'award_ceremony';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [
    ];

    /**
     * @var null|static 实例对象
     */
    protected static $instance = null;

    /**
     * 获取示例
     * @param array $options 实例配置
     * @return static
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) self::$instance = new self($options);

        return self::$instance;
    }

    protected function getContentAttr($value)
    {
        return $value ? json_decode($value, true) : [];
    }

    /**
     * 用户活动领奖
     * @param array $params
     * @param int $uid
     * @return bool
     * @throws
     */
    public function add(array $params, int $uid): bool
    {
        // 避免用户重复领取
        if ($this->where(['activity_id' => $params['activity_id'], 'goods_id' => $params['goods_id'], 'user_id' => $uid])->find()) {
            throw new Exception('请勿重复领取奖品');
        }
        Db::startTrans();
        try {
            $params['user_id'] = $uid;
            $params['createtime'] = date('Y-m-d H:i:s');
            $result = $this->allowField(true)->save(array_filter($params));
            if ($result) {
                Db::commit();
                return true;
            }
            throw new Exception('领取失败');
        } catch (Exception $exception) {
            Db::rollback();
            throw new Exception($exception->getMessage());
        }
    }

    public function activity()
    {
        return $this->hasOne(Activity::class, 'id', 'activity_id');
    }

    public function goods()
    {
        return $this->hasOne(Goods::class, 'id', 'goods_id');
    }

    public function address()
    {
        return $this->hasOne(Goods::class, 'id', 'address_id');
    }
}